package org.example.command;

import org.example.exception.HTMLDocumentException;
import org.example.model.HTMLDocument;
import org.jsoup.nodes.Element;

public class InsertElementCommand implements CanUndoCommand {

    private final HTMLDocument document;
    private final String tagName;
    private final String newElementId;
    private final String parentElementId;
    private final String textContent;
    private Element insertedElement;

    private InsertElementCommand(HTMLDocument document, String tagName, String newElementId, String parentElementId, String textContent) {
        this.document = document;
        this.tagName = tagName;
        this.newElementId = newElementId;
        this.parentElementId = parentElementId;
        this.textContent = textContent;
    }

    public static Command create(HTMLDocument document, String tagName, String newElementId, String parentElementId, String textContent) {
        return new InsertElementCommand(document, tagName, newElementId, parentElementId, textContent);
    }

    @Override
    public boolean execute() {
        try {
            insertedElement = document.insertElementBefore(tagName, newElementId, parentElementId, textContent);
        }
        catch (HTMLDocumentException e){
            System.out.println("Error: " + e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public void undo() {
        if (insertedElement != null) {
            insertedElement.remove(); // 撤销插入
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        InsertElementCommand other = (InsertElementCommand) obj;
        return this.newElementId.equals(other.newElementId) && this.parentElementId.equals(other.parentElementId);
    }

    @Override
    public int hashCode() {
        return newElementId.hashCode();
    }

    @Override
    public String toString() {
        return "InsertElementCommand{" + "newElementId='" + newElementId + "', parentElementId='" + parentElementId + "'}";
    }
}
